#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include "Mutex.hpp"

using namespace MutexModule;

int ticket = 100;
class ThreadData
{
public:
    ThreadData(const std::string &n, Mutex &l) : name(n), lockp(&l) {}
    ~ThreadData() {}
    std::string name;
    Mutex *lockp;
};

void *route(void *arg)
{
    ThreadData *td = static_cast<ThreadData *>(arg);

    while (1)
    {
        td->lockp->Lock();
        if (ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket:%d\n", td->name.c_str(), ticket);
            ticket--;
            td->lockp->UnLock();
        }
        else
        {
            td->lockp->UnLock();
            break;
        }
    }
}
int main(void)
{
    Mutex mutex;
    pthread_t t1, t2, t3, t4;
    ThreadData *td1 = new ThreadData("thread 1", mutex);
    pthread_create(&t1, NULL, route, td1);

    ThreadData *td2 = new ThreadData("thread 2", mutex);
    pthread_create(&t2, NULL, route, td2);

    ThreadData *td3 = new ThreadData("thread 3", mutex);
    pthread_create(&t3, NULL, route, td3);

    ThreadData *td4 = new ThreadData("thread 4", mutex);
    pthread_create(&t4, NULL, route, td4);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_join(t4, NULL);
}